<template>
    <div class="system-thirdapp-container">
        <el-dialog title="新增第三方应用" v-model="isShowDialog" >
            <el-form ref="addThirdAppFormRef" :model="formData" :rules="formRules" label-width="80px">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="应用名称" prop="appName">
                            <el-input v-model="formData.appName" placeholder="请输入应用名称" clearable></el-input>
                        </el-form-item>
                    </el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="应用状态" prop="status">
							<el-select v-model="formData.status" placeholder="请选择应用状态" clearable class="w100">
								<el-option label="正常" value="0"></el-option>
								<el-option label="停用" value="1"></el-option>
								<el-option label="删除" value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                        <el-form-item label="应用图标" prop="appLogo">
                            <el-input v-model="formData.appLogo" placeholder="请输入应用图标" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                        <el-form-item label="回调地址" prop="callbackUri">
                            <el-input v-model="formData.callbackUri" placeholder="请输入回调地址" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                        <el-form-item label="应用主页" prop="redirectUri">
                            <el-input v-model="formData.redirectUri" placeholder="请输入应用主页" clearable></el-input>
                        </el-form-item>
                    </el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="授权信息" prop="scopes">
							<el-select v-model="formData.scopes" multiple placeholder="请选择授权信息" clearable class="w100">
								<el-option
									v-for="item in scopeOptions"
									:key="item.value"
									:label="item.label"
									:value="item.value"
									:disabled="item.disabled">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="授权资源" prop="resourceIds">
							<el-cascader
								placeholder="请选择资源权限（可选填）"
								v-model="formData.resourceIds"
								:options="resources"
								:props="{expandTrigger: 'hover', multiple: true, value: 'id', label: 'name', children: 'children' }"
								collapse-tags
								class="w100"
								clearable>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="授权角色" prop="roleIds">
							<el-select v-model="formData.roleIds" multiple placeholder="请选择授权角色（可选填）" clearable class="w100">
								<el-option
									v-for="item in roles"
									:key="item.id"
									:label="item.roleName"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                        <el-form-item label="应用描述" prop="remark">
                            <el-input type="textarea" v-model="formData.remark" placeholder="请输入应用描述" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="onCancel">取 消</el-button>
                    <el-button type="primary" @click="onSubmit">保 存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { lineToTreeData } from '/@/utils/commonFunction';
import { getRoleList } from '/@/api/system/role/index';
import { getResourceList } from '/@/api/system/resource/index';
import { addThirdApp } from '/@/api/system/thirdapp/index';
export default {
    name: 'thirdapp/add',
    setup(props, context) {
        const addThirdAppFormRef = ref();
        const state = reactive({
            isShowDialog: false,
			scopeOptions: [{
				label: '用户信息',
				value: 'USER',
				disabled: true
			},{
				label: '邮箱账号',
				value: 'EMAIL'
			},{
				label: '手机号码',
				value: 'PHONE'
			},{
				label: '部门信息',
				value: 'DEPT'
			},{
				label: '角色信息',
				value: 'ROLE'
			},{
				label: '职级信息',
				value: 'RANK'
			}],
			roles: [],
			resources: [],
            formData: {
				status: '0',
				scopes: ['USER'],
				roleIds: [],
				resourceIds: [],
            },
            formRules : {
				appName: {required: true, message: '应用名称不能为空', trigger: 'blur' },
				callbackUri: {required: true, message: '回调地址不能为空', trigger: 'blur' },
				redirectUri: {required: true, message: '应用主页不能为空', trigger: 'blur' },
				scopes: { required: true, message: '授权信息不能为空', trigger: 'change' }
            }
        });
		//获取授权资源
		const loadResources = async () => {
			await getResourceList({status: '0', belong: 'OPEN'}).then((res) => {
				if(res.code == 0){
					res.data?.forEach(item => {
						item.name = item.name + (item.path ? `（${item.path}）` : '');
					});
					state.resources = lineToTreeData(res.data);
				}
			});
		}
        //获取角色
        const loadRoles = async () => {
			await getRoleList({pageNum: 1, pageSize: 1000}).then((res) => {
				if(res.code == 0){
					state.roles = res.data;
				}
			});
        }
        // 打开弹窗
        const openDialog = (row?: object) => {
            state.isShowDialog = true;
			loadRoles();
			loadResources();
        };
        // 关闭弹窗
        const closeDialog = (row?: object) => {
            state.isShowDialog = false;
            for(var key in state.formData) {
                state.formData[key] = undefined;
            }
            addThirdAppFormRef.value.resetFields();
        };
        // 取消
        const onCancel = () => {
            closeDialog();
        };
        // 新增
        const onSubmit = () => {
            addThirdAppFormRef.value.validate(valid => {
                if(valid){
					let resourceIds = [] as any;
					state.formData.resourceIds.forEach(items => {
						if(typeof items == 'string'){
							resourceIds.push(items);
						}else{
							items.forEach(item => {
								resourceIds.push(item);
							});
						}
					});
					resourceIds = Array.from(new Set(resourceIds));//去重
					
                    let params = {
                        appName: state.formData.appName,
                        appLogo: state.formData.appLogo,
						status: state.formData.status,
                        callbackUri: state.formData.callbackUri,
                        redirectUri: state.formData.redirectUri,
                        remark: state.formData.remark,
						scopes: state.formData.scopes,
						resourceIds: resourceIds,
						roleIds: state.formData.roleIds,
                    }
                    addThirdApp(params).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('保存成功');
                            context.emit('submit');
                            closeDialog();
                        }
                    });
                }
            });
        };
        return {
            addThirdAppFormRef,
            openDialog,
            closeDialog,
            onCancel,
            onSubmit,
            ...toRefs(state),
        };
    },
};
</script>